import { v4 as uuidv4 } from "uuid";
import {
  DeleteOutlined,
  PlusCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons";
import {
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Spin,
  Popover,
  Button,
  message,
} from "antd";
import { useEffect, useRef, useState } from "react";
import AddOption from "./AddOption";

const AddQuestion = ({ open, onOk, onCancel }) => {
  const [addingQuestion, setAddingQuestion] = useState({
    content: "",
    type: null,
    answer: "",
    diffcultLevel: 1,
    options: [
      { content: "", isRight: 0 },
      { content: "", isRight: 0 },
      { content: "", isRight: 0 },
      { content: "", isRight: 0 },
    ],
  });
  const [loading, setLoading] = useState(false);
  const [optionss, setOptionss] = useState([
    { options: [], answer: null },
    { options: [], answer: null, mode: "multiple" },
    {
      options: [
        { value: 1, label: <span>正确</span> },
        { value: 0, label: <span>错误</span> },
      ],
      answer: null,
      notShowAdd: true,
    },
    {
      options: [],
      mode: "multiple",
    },
  ]);
  const [addOptionShow, setAddOptionShow] = useState(false);
  const [answers, setAnswers] = useState([{ answer: null }]);
  useEffect(() => {
    setOptionss([
      { options: [], answer: null },
      { options: [], answer: null, mode: "multiple" },
      {
        options: [
          { value: 1, label: <span>正确</span> },
          { value: 0, label: <span>错误</span> },
        ],
        answer: null,
        notShowAdd: true,
      },
      {
        options: [],
        mode: "multiple",
      },
    ]);
    setAnswers([{ answer: null }]);
    setAddingQuestion({
      content: "",
      type: null,
      answer: "",
      diffcultLevel: 1,
      options: [
        { content: "", isRight: 0 },
        { content: "", isRight: 0 },
        { content: "", isRight: 0 },
        { content: "", isRight: 0 },
      ],
    });
  }, [open]);
  const submitBtn = useRef(null);
  const addOption = (content) => {
    setAddOptionShow(false);
    var temp = optionss.map((d, i) => {
      if (i === addingQuestion.type - 1) {
        d.options.push({ label: content, value: content, key: uuidv4() });
      }
      return d;
    });
    setOptionss(temp);
  };
  const SelectComponent = ({ index }) => {
    return (
      <div style={{ display: "flex" }}>
        <Select
          disabled={optionss[index].disabled}
          mode={optionss[index].mode}
          value={optionss[index].answer}
          dropdownRender={(node) => {
            return (
              <>
                {node}
                <Button
                  block
                  onClick={() => {
                    var temp = optionss.map((d, i) => {
                      if (i === index) {
                        var option = d.options.pop();
                        if (option === undefined || option.value === d.answer) {
                          d.answer = null;
                        }
                      }
                      return d;
                    });
                    setOptionss(temp);
                  }}
                >
                  <DeleteOutlined />
                </Button>
              </>
            );
          }}
          onChange={(value) => {
            var temp = optionss.map((d, i) => {
              if (i === index) {
                d.answer = value;
              }
              return d;
            });
            setOptionss(temp);
          }}
          options={optionss[index].options}
          placeholder="请选择"
        ></Select>
        &nbsp;&nbsp;
        {optionss[index].notShowAdd ? null : (
          <Button
            onClick={() => {
              setAddOptionShow(true);
            }}
          >
            <PlusCircleOutlined style={{ cursor: "pointer" }} />
          </Button>
        )}
      </div>
    );
  };
  const sharedProps = (type) => {
    return {
      label: (
        <>
          <span
            style={{
              display: "inline-block",
              marginInlineEnd: "4px",
              color: "#ff4d4f",
              fontSize: "14px",
              fontFamily: "SimSun, sans-serif",
              lineHeight: 1,
            }}
          >
            *
          </span>
          正确答案
        </>
      ),
      name: `answer`,
      rules: [
        {
          validator: () => {
            if (
              optionss[type - 1].answer == null ||
              optionss[type - 1].answer.length === 0
            ) {
              return Promise.reject("请选择正确答案！");
            } else if (type < 4 && optionss[type - 1].options.length < 2) {
              return Promise.reject("请至少添加两个选项！");
            } else {
              return Promise.resolve();
            }
          },
        },
      ],
    };
  };
  const FormItemComponent = ({ type }) => {
    switch (type) {
      case 1:
        return (
          <Form.Item {...sharedProps(type)}>
            <SelectComponent index={type - 1} />
          </Form.Item>
        );
      case 2:
        return (
          <Form.Item {...sharedProps(type)}>
            <SelectComponent index={1} />
          </Form.Item>
        );
      case 3:
        return (
          <Form.Item {...sharedProps(type)}>
            <SelectComponent index={2} />
          </Form.Item>
        );
      case 4:
        return (
          <Form.Item {...sharedProps(type)}>
            <SelectComponent index={3} />
          </Form.Item>
        );
      default:
        return null;
    }
  };
  return (
    <Modal
      centered={true}
      title="添加题目"
      open={open}
      onOk={() => submitBtn.current.click()}
      onCancel={onCancel}
      okText="添加"
      cancelText="取消"
      destroyOnClose={true}
    >
      <AddOption
        open={addOptionShow}
        onOk={addOption}
        onCancel={() => setAddOptionShow(false)}
      />
      <Spin
        spinning={loading}
        tip="正在提交..."
        size="large"
        fullscreen={true}
      ></Spin>
      <Form
        labelCol={{
          span: 6,
        }}
        wrapperCol={{
          span: 16,
        }}
        layout="horizontal"
        onFinish={async (values) => {
          if (values === undefined) {
            message.error("请填写完整信息！");
            return;
          }
          var temp = values;
          console.log(temp, "------------------");
          if ([1, 3].includes(addingQuestion.type)) {
            temp.options = optionss[addingQuestion.type - 1].options.map(
              (d) => {
                return {
                  content: d.value,
                  isRight:
                    (d.value === optionss[addingQuestion.type - 1].answer) + 0,
                };
              }
            );
          } else if ([2, 4].includes(addingQuestion.type)) {
            temp.options = optionss[addingQuestion.type - 1].options.map(
              (d) => {
                return {
                  content: d.value,
                  isRight:
                    optionss[addingQuestion.type - 1].answer.includes(d.value) +
                    0,
                };
              }
            );
          }
          setLoading(true);
          await onOk(temp);
          setLoading(false);
          // onOk(values);
        }}
      >
        <Form.Item
          label={
            <>
              <Popover
                content={
                  <>
                    <p>如果是填空题请使用占位符“{"{0}"}”</p>
                    <p>占位符如果多于选项数剩余的占位符将正常输出</p>
                  </>
                }
                title="说明"
              >
                <QuestionCircleOutlined style={{ cursor: "pointer" }} />
              </Popover>
              &nbsp;&nbsp;题目内容
            </>
          }
          name="content"
          rules={[
            { required: true, message: "请输入题目内容！" },
            {
              validator: () => {
                if (
                  addingQuestion.type === 4 &&
                  addingQuestion.content.split("{0}").length - 1 <
                    optionss[addingQuestion.type - 1].options.length
                ) {
                  return Promise.reject("题目内容中的占位符不能小于选项数！");
                } else {
                  return Promise.resolve();
                }
              },
            },
          ]}
        >
          <Input.TextArea
            rows={4}
            value={addingQuestion.content}
            onChange={(e) => {
              setAddingQuestion({ ...addingQuestion, content: e.target.value });
            }}
          />
        </Form.Item>
        <Form.Item
          label="题目类型"
          name="type"
          rules={[{ required: true, message: "请选择题目类型！" }]}
        >
          <Select
            value={addingQuestion.type}
            onChange={(value) => {
              setAddingQuestion({ ...addingQuestion, type: value });
              setOptionss(
                optionss.map((d, i) => {
                  if (i === value - 1) {
                    d.answer = null;
                  }
                  return d;
                })
              );
            }}
            placeholder="请选择"
          >
            <Select.Option value={1}>单选题</Select.Option>
            <Select.Option value={2}>多选题</Select.Option>
            <Select.Option value={3}>判断题</Select.Option>
            <Select.Option value={4}>填空题</Select.Option>
            <Select.Option value={5}>解答题</Select.Option>
          </Select>
        </Form.Item>
        <FormItemComponent type={addingQuestion.type} />
        <Form.Item
          label="正确答案"
          style={{ display: addingQuestion.type !== 5 ? "none" : "block" }}
          name="answer"
          rules={[
            {
              validator: () => {
                if (
                  addingQuestion.type === 5 &&
                  (answers[0].answer == null || answers[0].answer.length === 0)
                ) {
                  return Promise.reject("请填写正确答案！");
                } else {
                  return Promise.resolve();
                }
              },
            },
          ]}
        >
          <Input.TextArea
            rows={4}
            placeholder="请输入答案"
            value={answers[0].answer}
            onChange={(e) => {
              var temp = answers.map((d, i) => {
                if (i === 0) {
                  d.answer = e.target.value;
                }
                return d;
              });
              setAnswers(temp);
            }}
          />
        </Form.Item>
        <Form.Item
          label={
            <>
              <Popover
                content={
                  <>
                    <p>难度等级 1-99简单 100-199中等 200-299较难 300-399困难</p>
                    <p>400-499超难 500-599 极难 600-699 噩梦。</p>
                    <p> 700-10000 如果未定义难度等级，默认为'无限难度' </p>
                  </>
                }
                title="说明"
              >
                <QuestionCircleOutlined style={{ cursor: "pointer" }} />
              </Popover>
              &nbsp;&nbsp;难度等级
            </>
          }
          name="diffcultLevel"
          rules={[{ required: true, message: "请输入难度等级" }]}
        >
          <InputNumber
            min={1}
            max={10000}
            value={addingQuestion.diffcultLevel}
            onChange={(value) => {
              setAddingQuestion({ ...addingQuestion, diffcultLevel: value });
            }}
          />
        </Form.Item>
        <button
          ref={submitBtn}
          type="submit"
          style={{ display: "none" }}
        ></button>
      </Form>
    </Modal>
  );
};

export default AddQuestion;
